<template>
  <div class="home">
    <el-container class="full-height">
      <el-header>
        <div class="header-content">
          <div class="header-left">
            <h1>OTA管理系统</h1>
            <div class="nav-buttons">
              <el-button type="primary" size="small" @click="router.push('/security')">
                <el-icon><Lock /></el-icon>
                安全管理
              </el-button>
            </div>
          </div>
          <div class="user-info">
            <span class="username">欢迎，{{ userInfo?.username }}</span>
            <el-button type="danger" size="small" @click="handleLogout">
              <el-icon><SwitchButton /></el-icon>
              登出
            </el-button>
          </div>
        </div>
      </el-header>
      
      <el-main>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-card class="compact-card">
              <template #header>
                <div class="card-header">
                  <span>产品管理</span>
                  <el-button type="primary" @click="showCreateDialog = true">
                    <el-icon><Plus /></el-icon>
                    新增产品
                  </el-button>
                </div>
              </template>
              
              <el-table :data="products" v-loading="loading" style="width: 100%" size="small">
                <el-table-column prop="name" label="产品名称" />
                <el-table-column prop="public_id" label="公共产品ID" />
                <el-table-column prop="latest_version" label="最新版本" />
                <el-table-column prop="sign_type" label="签名类型" />
                <el-table-column prop="created_at" label="创建时间">
                  <template #default="scope">
                    {{ formatDate(scope.row.created_at) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                  <template #default="scope">
                    <el-button size="small" @click="viewProduct(scope.row)">
                      查看
                    </el-button>
                    <el-button size="small" type="primary" @click="editProduct(scope.row)">
                      编辑
                    </el-button>
                    <el-button size="small" type="danger" @click="deleteProduct(scope.row)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-col>
        </el-row>
      </el-main>
    </el-container>

    <!-- 创建产品对话框 -->
    <el-dialog v-model="showCreateDialog" title="新增产品" width="500px">
      <el-form :model="createForm" :rules="rules" ref="createFormRef" label-width="120px">
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="createForm.name" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="公共产品ID" prop="public_id">
          <el-input v-model="createForm.public_id" placeholder="请输入公共产品ID" />
        </el-form-item>
        <el-form-item label="最新版本" prop="latest_version">
          <el-input v-model="createForm.latest_version" placeholder="请输入最新版本" />
        </el-form-item>
        <el-form-item label="签名类型" prop="sign_type">
          <el-select v-model="createForm.sign_type" placeholder="请选择签名类型">
            <el-option label="HMAC_SHA512" value="HMAC_SHA512" />
          </el-select>
        </el-form-item>
        <el-form-item label="签名密钥" prop="sign_key">
          <el-input v-model="createForm.sign_key" placeholder="请输入签名密钥" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="createProduct" :loading="creating">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑产品对话框 -->
    <el-dialog v-model="showEditDialog" title="编辑产品" width="500px">
      <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="120px">
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="公共产品ID" prop="public_id">
          <el-input v-model="editForm.public_id" placeholder="请输入公共产品ID" />
        </el-form-item>
        <el-form-item label="最新版本" prop="latest_version">
          <el-input v-model="editForm.latest_version" placeholder="请输入最新版本" />
        </el-form-item>
        <el-form-item label="签名类型" prop="sign_type">
          <el-select v-model="editForm.sign_type" placeholder="请选择签名类型">
            <el-option label="HMAC_SHA512" value="HMAC_SHA512" />
          </el-select>
        </el-form-item>
        <el-form-item label="签名密钥" prop="sign_key">
          <el-input v-model="editForm.sign_key" placeholder="请输入签名密钥" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="updateProduct" :loading="updating">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, SwitchButton, Lock } from '@element-plus/icons-vue'
import { productService, type Product, type CreateProductRequest, type UpdateProductRequest } from '@/services/productService'
import { authService } from '@/services/authService'

const router = useRouter()

// 用户信息
const userInfo = ref(authService.getUserInfo())

// 响应式数据
const products = ref<Product[]>([])
const loading = ref(false)
const creating = ref(false)
const updating = ref(false)
const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const currentProduct = ref<Product | null>(null)

// 表单数据
const createForm = ref<CreateProductRequest>({
  name: '',
  public_id: '',
  latest_version: '',
  sign_type: 'HMAC_SHA512',
  sign_key: ''
})

const editForm = ref<UpdateProductRequest>({
  name: '',
  public_id: '',
  latest_version: '',
  sign_type: '',
  sign_key: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入产品名称', trigger: 'blur' }
  ],
  public_id: [
    { required: true, message: '请输入公共产品ID', trigger: 'blur' }
  ],
  sign_type: [
    { required: true, message: '请选择签名类型', trigger: 'change' }
  ],
  sign_key: [
    { required: true, message: '请输入签名密钥', trigger: 'blur' }
  ]
}

// 表单引用
const createFormRef = ref()
const editFormRef = ref()

// 获取产品列表
const loadProducts = async () => {
  loading.value = true
  try {
    products.value = await productService.getProducts()
  } catch (error) {
    ElMessage.error('获取产品列表失败')
  } finally {
    loading.value = false
  }
}

// 创建产品
const createProduct = async () => {
  if (!createFormRef.value) return
  
  await createFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      creating.value = true
      try {
        await productService.createProduct(createForm.value)
        ElMessage.success('产品创建成功')
        showCreateDialog.value = false
        createForm.value = { name: '', public_id: '', latest_version: '', sign_type: 'HMAC_SHA512', sign_key: '' }
        loadProducts()
      } catch (error) {
        ElMessage.error('产品创建失败')
      } finally {
        creating.value = false
      }
    }
  })
}

// 编辑产品
const editProduct = (product: Product) => {
  currentProduct.value = product
  editForm.value = {
    name: product.name,
    public_id: product.public_id,
    latest_version: product.latest_version,
    sign_type: product.sign_type,
    sign_key: product.sign_key
  }
  showEditDialog.value = true
}

// 更新产品
const updateProduct = async () => {
  if (!editFormRef.value || !currentProduct.value) return
  
  await editFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      updating.value = true
      try {
        await productService.updateProduct(currentProduct.value!.id, editForm.value)
        ElMessage.success('产品更新成功')
        showEditDialog.value = false
        loadProducts()
      } catch (error) {
        ElMessage.error('产品更新失败')
      } finally {
        updating.value = false
      }
    }
  })
}

// 删除产品
const deleteProduct = async (product: Product) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除产品 "${product.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await productService.deleteProduct(product.id)
    ElMessage.success('产品删除成功')
    loadProducts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('产品删除失败')
    }
  }
}

// 查看产品详情
const viewProduct = (product: Product) => {
  // 跳转到产品详情页面
  router.push(`/product/${product.id}`)
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString()
}

// 处理登出
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要登出吗？',
      '确认登出',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    authService.logout()
    ElMessage.success('登出成功')
    router.push('/login')
  } catch (error) {
    // 用户取消登出
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadProducts()
})
</script>

<style scoped>
.home {
  height: 100vh;
  width: 100%;
  overflow-x: hidden;
}

.full-height {
  height: 100%;
}

.el-header {
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
  height: 50px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  max-width: 1200px;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-content h1 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.nav-buttons {
  display: flex;
  gap: 8px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.username {
  color: #666;
  font-size: 14px;
}

.el-main {
  padding: 10px;
  height: calc(100vh - 50px);
  overflow-y: auto;
  overflow-x: hidden;
}

.compact-card {
  margin: 0;
}

.compact-card :deep(.el-card__body) {
  padding: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
